﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ExamDemo.Data;
using ExamDemo.Models;
using ExamDemo.ViewModel;

namespace MVCDemo.Controllers
{
    public class MessagesController : Controller
    {
        private ExamDemoDb db = new ExamDemoDb();

        // GET: Messages
        public ActionResult Index()
        {
            var username = Session["username"] == null ? "" : Session["username"].ToString();

            if (username.Length > 0)
            {
                var users = db.Users.ToList();
                var msgs = db.Messages.ToList();
                var cmgs = db.Comments.ToList();

                var msgViewModeList = new List<MessageViewModel>();

                // 将所有的消息，转换为视图需要的模型
                foreach (var msg in msgs)
                {
                    var cmgViewModeList = new List<CommentViewModel>();

                    // 先找到当前说说对应的所有的评论
                    var tmpComments = cmgs.Where(x => x.MsgId == msg.Id).ToList();

                    // 遍历找到的所有评论，并将其转换为对应的视图模型
                    foreach (var cmg in tmpComments)
                    {
                        // 找到发表评论的用户
                        var fromUser = users.Where(x => x.Id == cmg.FromUserId).FirstOrDefault();//linq
                                                                                                 // 找到对哪个说说进行的评论
                        var m = msgs.Where(x => x.Id == cmg.MsgId).FirstOrDefault();
                        // 再根据找到的说说，进而找到发表说说的用户
                        var toUser = users.Where(x => x.Id == m.FromUserId).FirstOrDefault();

                        cmgViewModeList.Add(new CommentViewModel
                        {
                            FromUsername = fromUser.Username,
                            ToUsername = toUser.Username,
                            Comment = cmg.Comment
                        });
                    }

                    // 将消息转换为消息的视图模型
                    msgViewModeList.Add(new MessageViewModel
                    {
                        Id = msg.Id,
                        Content = msg.Content,
                        CommentViewModels = cmgViewModeList
                    });
                }



                var vm = new SayViewModel
                {
                    Username = "一天到晚游泳的鱼",
                    MessageViewModel = msgViewModeList
                };

                return View(vm);
            }
            else
            {
                Response.Redirect("/users/login");
                return View(new SayViewModel());
            }




        }

        // GET: Messages/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // GET: Messages/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Messages/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,FromUserId,Content,CreatedAt,UpdatedAt,Version,Remarks")] Messages messages)
        {
            if (ModelState.IsValid)
            {
                db.Messages.Add(messages);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(messages);
        }

        // GET: Messages/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // POST: Messages/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,FromUserId,Content,CreatedAt,UpdatedAt,Version,Remarks")] Messages messages)
        {
            if (ModelState.IsValid)
            {
                db.Entry(messages).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(messages);
        }

        // GET: Messages/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Messages messages = db.Messages.Find(id);
            if (messages == null)
            {
                return HttpNotFound();
            }
            return View(messages);
        }

        // POST: Messages/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Messages messages = db.Messages.Find(id);
            db.Messages.Remove(messages);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
